// 商品列表组件
<template>
    <SearchBox @startSearch="refresh" />
    <div class="el-card-up" v-loading="loading" element-loading-text="数据请求中。。。">
        <!-- 真正展示内容区域 -->
        <Productinfo v-for="product in productList" :key=product.id :productInfo=product />
        <!-- <el-empty v-if="total == 0" description="暂无数据" style="width: 100%;" /> -->
        <el-empty v-if="total == 0" description="No Data" style="width: 100%;" />
        <div class="el-card-pagination" v-if="total > 0">
            <el-pagination background size="large" layout="prev, pager, next" :total="total" :page-size="pageSize"
                @current-change="handlePageChange" />
        </div>
    </div>
</template>

<script lang='ts' setup>
import { aa } from '@/api/typemapping';
import { HttpMethod } from '@/api/types';
import { apiRequest } from '@/api/apiService';
import { ref, reactive, onMounted } from 'vue';
import SearchBox from '@/components/commerce/SearchBox.vue';
import Productinfo from '@/components/commerce/Productinfo.vue';

const loading = ref(false);         // loading标识
const productList = ref();          // 响应数据
const total = ref<number>(0);       // 总条目数
const pageSize = ref<number>(10);   // 每页显示条目数
const searchText = ref<string>(''); // 搜索框输入值
const currentPage = ref<number>(1); // 当前页码
const listParam = reactive({        // 列表请求参数
    keyword: '',
    page_number: 1,
    page_size: 10
})

// 使用 onMounted 生命周期钩子在应用挂载后运行初始化函数
onMounted(() => {
    refresh('');
});

// 处理页码切换的事件
const handlePageChange = (page: number) => {
    currentPage.value = page;
    // 在这里添加你需要在页码切换时执行的逻辑
    refresh(searchText.value);
};

// 假设你有一个需要刷新的方法
const refreshList = () => {
    getCommodityList();
};

// 刷新方法
const refresh = (data: string) => {
    searchText.value = data;
    loading.value = true;
    listParam.keyword = data;
    listParam.page_number = currentPage.value;
    listParam.page_size = pageSize.value;
    refreshList();
};

// 发起获取商品列表请求
const getCommodityList = async () => {
    try {
        const url = '/commodity/list';
        const response = await apiRequest.request<any>(HttpMethod.POST, url, listParam);
        productList.value = response.data;
        total.value = response.total;
        loading.value = false;
    } catch (error) {
        console.log('request: /api/commodity/list failed, error message: ', error);
        loading.value = false;
    }
};
</script>

<style scoped>
.el-card-up {
    padding: 0 1vw;
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20px;
}

.el-card-pagination {
    justify-content: flex-end;
    display: flex;
    width: 93%;
}

body {
    margin: 0;
}
</style>